import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
import { apiBaseURL } from './baseURL'
import type { IResult, IResultData, IResultList } from '../types'
//import { ElMessage, ElLoading } from 'element-plus'
//import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
//import { useRouter } from 'vue-router'
import type { IAuthUser } from '~/types/system'

//import { storeToRefs } from "pinia"
import store from '../store/index'

type TAxiosOption = {
  baseURL: string;
  timeout: number;
}
const config = {
  headers: {
    'Content-Type': 'application/json',
  },
  baseURL: apiBaseURL,
  timeout: 120000
}

//let loading: LoadingInstance;

class Http {
  service: AxiosInstance;
  constructor(config: TAxiosOption) {
    this.service = axios.create(config)

    /* 请求拦截  this.service.interceptors.request.use(config => config, error => Promise.reject(error))*/
    this.service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      /* 业务逻辑
      1. 开启全屏loading动画
      2. 数据加密config.data
      3. 请求头加上token，结合vuex或localstorage：
          if(store.getters.token) config.headers['x-token'] = store.getters.token
          else 重定向
      4. ……
      */
      /* loading = ElLoading.service({
        lock: true,
        // text: '正在努力加载中...',
        spinner: `
            <path class="path" d="
              M 30 15
              L 28 17
              M 25.61 25.61
              A 15 15, 0, 0, 1, 15 30
              A 15 15, 0, 1, 1, 27.99 7.5
              L 15 15
            " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
          `,
        svgViewBox: '-10, -10, 50, 50',
        background: 'rgba(255, 255, 255, 0)',
      }) */

      //pinia 中获取 token
      /* const { token } = storeToRefs(store())
      if (token.value.length > 0) {
        config.headers.Authorization = 'Bearer ' + token.value
      } */

      //获取 jwt token
      const storedUser = sessionStorage.getItem('user');
      if (storedUser) {
        const user: IAuthUser = JSON.parse(storedUser);
        //console.log('user.token: ', user.token);
        if (user.token.length > 0) {
          config.headers.Authorization = 'Bearer ' + user.token
        }
      }

      return config
    }, error => {
      /* 请求错误 
      1. 关闭全屏loading动画
      2. 重定向到错误页
      */
      //loading.close()
      return Promise.reject(error) // 为了可以在代码中catch到错误信息
    })

    /* 响应拦截   this.service.interceptors.response.use(response => response.data, error => Promise.reject(error))*/
    this.service.interceptors.response.use((response: AxiosResponse<any>) => {
      /* 
      1. 关闭全屏loading动画
      2. 数据解密
      3. 根据 response.data.code 做不同的错误处理
      4. ……
      */
      //loading.close()

      const data = response.data

      const { code, msg } = data
      if (code < 0) {
        /* ElMessage.error(msg) */
        console.log('msg: ', msg);
        return Promise.reject(data)
      }

      return data
    }, error => {
      //loading.close()
      // 这里用来处理http常见错误，进行全局提示
      let message = "";
      switch (error.response.status) {
        case 400:
          message = "请求错误(400)";
          break;
        case 401:
          message = "未授权，请重新登录(401)";
          // 这里可以做清空storage并跳转到登录页的操作
          localStorage.clear();
          sessionStorage.clear();
          location.href = "/login";
          break;
        case 403:
          message = "拒绝访问(403)";
          break;
        case 404:
          message = "请求出错(404)";
          break;
        case 408:
          message = "请求超时(408)";
          break;
        case 500:
          message = "服务器错误(500)";
          break;
        case 501:
          message = "服务未实现(501)";
          break;
        case 502:
          message = "网络错误(502)";
          break;
        case 503:
          message = "服务不可用(503)";
          break;
        case 504:
          message = "网络超时(504)";
          break;
        case 505:
          message = "HTTP版本不受支持(505)";
          break;
        default:
          message = `连接出错(${error.response.status})`;
      }
      //ElMessage.error(`${message},请检查网络或联系管理员！`)
      console.log('message: ', message);
      return Promise.reject(error.response)
    })
  }
  getList<T>(url: string, params?: object, _object = {}): Promise<IResultList<T>> {
    return this.service.get(url, { params, ..._object })
  }
  get<T>(url: string, params?: object, _object = {}): Promise<IResultData<T>> {
    return this.service.get(url, { params, ..._object })
  }
  post(url: string, params?: object, _object = {}): Promise<IResult> {
    return this.service.post(url, params, _object)
  }
  put(url: string, params?: object, _object = {}): Promise<IResult> {
    return this.service.put(url, params, _object)
  }
  delete(url: string, params?: any, _object = {}): Promise<IResult> {
    return this.service.delete(url, { params, ..._object })
  }
  deleteBatch(url: string, params?: any, _object = {}): Promise<IResult> {
    return this.service.delete(url, { data: params, ..._object })
  }
}

export default new Http(config)